package com.freesky.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserDtbankcustChannelvoucherSendRequest;
import com.alipay.api.response.AlipayUserDtbankcustChannelvoucherSendResponse;
import com.freesky.biz.activity.domain.TAlipayCouponDetail;
import com.freesky.biz.activity.mapper.CouponDetailMapper;
import com.freesky.biz.citic.domain.TCiticLucky;
import com.freesky.biz.citic.domain.TCiticNew;
import com.freesky.biz.citic.mapper.CiticLuckyMapper;
import com.freesky.biz.citic.mapper.CiticNewMapper;
import com.freesky.biz.citic.service.CiticSendService;
import com.freesky.biz.external.service.*;
import com.freesky.biz.pay.config.AliPayConfiguration;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.constant.Constants;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 中信富贵新客礼
 */
@Component("citicNewTask")
public class CiticNewTask {

    private static final Logger logger = LoggerFactory.getLogger(CiticNewTask.class);

    @Autowired
    private CiticNewMapper citicNewMapper;

    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Autowired
    private MobileCmccService mobileCmccService;

    @Autowired
    private MobileRechargeBlueService mobileRechargeBlueService;

    @Autowired
    private MobileJulivesService mobileJulivesService;

    @Autowired
    private MobileJuCaiService mobileJuCaiService;

    @Autowired
    private CiticSendService citicSendService;

    @Autowired
    private AliPayConfiguration aliPayConfiguration;

    /**
     * 信运抢券的任务处理
     */
    public void taskProcess() {
        logger.info("citicNewMapper task start");
        List<TCiticNew> citicNewList = citicNewMapper.selectUnProcessList();
        for(TCiticNew citicNew : citicNewList){
            if("1".equalsIgnoreCase(citicNew.getFavourFlag())) {
                int nCount = citicNewMapper.getReceiveCount(citicNew.getCustId(),
                        citicNew.getBusiType());
                if (nCount > 0) {
                    citicRefund(citicNew, "退款：已享受优惠!");
                    continue;
                }
            }

            citicNewMapper.updateProcessedById("2",citicNew.getId());

            //发放类型，5001、微信立减金，5002支付宝红包，5003话费充值
            if("5002".equalsIgnoreCase(citicNew.getType())){
                grantAlipayCoupon(citicNew);
            } else if("5003".equalsIgnoreCase(citicNew.getType())){
                if (StringUtils.isEmpty(citicNew.getChannel())) {
                    sendMobileCmccRecharge(citicNew);
                } else if ("移动".equalsIgnoreCase(citicNew.getChannel())) {
                    sendMobileRechargeJuCai(citicNew);
                } else if ("聚采".equalsIgnoreCase(citicNew.getChannel())) {
                    sendMobileRechargeBlue(citicNew);
                } else {
                    sendMobileRechargeJulive(citicNew);
                }
            }
        }
    }

    //蓝色
    public void sendMobileRechargeBlue(TCiticNew citicNew){
        try{
            citicNew.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileRechargeBlueService.sendMobileRecharge(
                    "CITIC_" + citicNew.getLastReqId(),
                    String.valueOf(citicNew.getAmt()),
                    citicNew.getMobile());

            citicNew.setChannel("蓝色");
            citicNew.setRespCode(result.get("code").toString());
            citicNew.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                citicNew.setProcessed("2");
                citicNew.setRechargeId(result.get("data").toString());
            } else {
                citicNew.setProcessed("3");
            }
            citicNewMapper.updateProcessedResultById(citicNew);
            citicNewMapper.insertIntegralMobileLog(citicNew);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-蓝色接口",ioe.getMessage());
        }
    }

    public void sendMobileRechargeJulive(TCiticNew citicNew){
        try{
            citicNew.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileJulivesService.sendMobileRecharge(
                    "CITIC_" + citicNew.getLastReqId(),
                    String.valueOf(citicNew.getAmt()),
                    citicNew.getMobile());

            citicNew.setChannel("智信");
            citicNew.setRespCode(result.get("code").toString());
            citicNew.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                citicNew.setRechargeId(result.get("data").toString());
                citicNew.setProcessed("2");
            } else {
                citicNew.setProcessed("3");
            }
            citicNewMapper.updateProcessedResultById(citicNew);
            citicNewMapper.insertIntegralMobileLog(citicNew);
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-智信接口",ioe.getMessage());
        }
    }

    public void sendMobileRechargeJuCai(TCiticNew citicNew){
        try{
            citicNew.setLastReqId(SeqUtil.getSeqId());
            AjaxResult result = mobileJuCaiService.sendMobileRecharge(
                    "CITIC_" + citicNew.getLastReqId(),
                    String.valueOf(citicNew.getAmt()),
                    citicNew.getMobile());
            citicNew.setChannel("聚采");
            citicNew.setRespCode(result.get("code").toString());
            citicNew.setRespMsg(result.getMsg());

            if(result.isSuccess()){
                citicNew.setRechargeId("");
                citicNew.setProcessed("2");
            } else {
                citicNew.setProcessed("3");
            }
            citicNewMapper.updateProcessedResultById(citicNew);
            citicNewMapper.insertIntegralMobileLog(citicNew);
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-积分兑话费-智信接口",ioe.getMessage());
        }
    }

    //移动充值
    public void sendMobileCmccRecharge(TCiticNew citicNew){
        try{
            String seqId = SeqUtil.getSeqId();
            AjaxResult result = mobileCmccService.sendMobileRecharge(
                    seqId,
                    String.valueOf(Integer.parseInt(citicNew.getAmt())*10),
                    citicNew.getMobile());
            citicNew.setLastReqId(seqId);
            citicNew.setChannel("移动");
            if(result.isSuccess()) {
                citicNew.setRespCode(Constants.SUCCESS);
                citicNew.setRespMsg("充值成功");
                citicNew.setProcessed("4");
                citicNew.setRechargeId(seqId);
                citicNew.setState("1");
            } else {
                citicNew.setRespCode(Constants.FAIL);
                citicNew.setRespMsg(result.getMsg());
                citicNew.setProcessed("3");
            }
            citicNewMapper.updateProcessedResultById(citicNew);
            citicNewMapper.insertIntegralMobileLog(citicNew);
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-批充-移动接口",ioe.getMessage());
        }
    }

    //支付宝通用红包
    public void grantAlipayCoupon(TCiticNew citicNew){
        try{
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            certAlipayRequest.setServerUrl(aliPayConfiguration.getGatewayUrl());
            certAlipayRequest.setAppId(aliPayConfiguration.getAppId());
            certAlipayRequest.setPrivateKey(aliPayConfiguration.getPrivateKey());
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset(aliPayConfiguration.getCharset());
            certAlipayRequest.setSignType(aliPayConfiguration.getSignType());
            certAlipayRequest.setCertPath(aliPayConfiguration.getAppCertPath());
            certAlipayRequest.setAlipayPublicCertPath(aliPayConfiguration.getAlipayCertPath());
            certAlipayRequest.setRootCertPath(aliPayConfiguration.getAlipayRootCertPath());
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

            AlipayUserDtbankcustChannelvoucherSendRequest request = new AlipayUserDtbankcustChannelvoucherSendRequest();

//            中信富贵新客礼300：18777988
//            中信富贵新客礼100：18780182
//            中信支付宝富贵新客礼300：ACT190CCV02149050
//            中信支付宝富贵新客礼100：ACT490CCV02147894
            if("1001".equalsIgnoreCase(citicNew.getBusiType())){
                request.setBizContent("{" +
                        "  \"phone_id\":\"" + citicNew.getMobile() + "\"," +
                        "  \"activity_id\":\"ACT190CCV02776154\"," +
                        "  \"out_biz_no\":\"" + citicNew.getId() + "\"" +
                        "}");
            } else if("1002".equalsIgnoreCase(citicNew.getBusiType())){
                request.setBizContent("{" +
                        "  \"phone_id\":\"" + citicNew.getMobile() + "\"," +
                        "  \"activity_id\":\"ACT290CCV02777742\"," +
                        "  \"out_biz_no\":\"" + citicNew.getId() + "\"" +
                        "}");
            } else {
                return ;
            }


            // 支付宝通用红包Resp:{"activityId":"ACT190CCV00515644","activityOrderId":"20220324180321ACT09393CCV00051406428","body":"{\"alipay_user_dtbankcust_channelvoucher_send_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"activity_id\":\"ACT190CCV00515644\",\"activity_order_id\":\"20220324180321ACT09393CCV00051406428\",\"discount_threshold_amt\":1001,\"discount_type\":\"reduce\",\"discount_value\":1000,\"send_amount\":1000,\"send_status\":\"SUCCESS\",\"voucher_id\":\"202203240007300293240AZCWK1F\"},\"alipay_cert_sn\":\"a7456c1d07b0d38c65d5de409b519d6b\",\"sign\":\"Mp/agpDS5+HUChJcnUnGfiKJb970ydZYNFseFji2FhFAbRFIesJIMXwnaDnBI8vSzRlQjf7GRRDTPYJlWehVmD/XrPNpbSqJK0kmi8OGgBO9vAA8vI7liq8NkenOa7wEe1RqTzjiHIRI4BHoGOPTQiugOLoUpG9vQztcso6eQXr+gCBZkBcqi0GXVbr7137aZcYQ94juZI7UjES0GYOEUbjXq2gBik8cawpT0iTkWfQk1IwHQKQ5bcjC1L4eh11LMwbyHG4zXzJo1ZUnnbIH3NqemYSTtGqcYmpBfta7wkIw7O201NnogNywX6QJ3Ry9EJMJ3BsCR2ENZYhBoIhqqQ==\"}","code":"10000","discountThresholdAmt":1001,"discountType":"reduce","discountValue":1000,"errorCode":"10000","msg":"Success","params":{"biz_content":"{  \"user_id\":\"2088512933424935\",  \"activity_id\":\"ACT190CCV00515644\",  \"out_biz_no\":\"956578649744740352\"}"},"sendAmount":1000,"sendStatus":"SUCCESS","success":true,"voucherId":"202203240007300293240AZCWK1F"}
            logger.info("支付宝通用红包Req:"+request.getBizContent());
            AlipayUserDtbankcustChannelvoucherSendResponse response = alipayClient.certificateExecute(request);
            logger.info("支付宝通用红包Resp:"+ JSON.toJSONString(response));

            if (response.isSuccess()){
                citicNew.setChannel("支付宝");
                citicNew.setRefundFlag("0");
                citicNew.setRespMsg("已下发红包");
                citicNew.setProcessed("4");

                citicNewMapper.updateProcessedResultById(citicNew);

                TAlipayCouponDetail alipayCouponModel = new TAlipayCouponDetail();
                alipayCouponModel.setId(SeqUtil.getSeqId());
                alipayCouponModel.setAppId("");
                alipayCouponModel.setActivityId(response.getActivityId());
                alipayCouponModel.setActivityOrderId(response.getActivityOrderId());
                alipayCouponModel.setVoucherId(response.getVoucherId());
                alipayCouponModel.setAmt(citicNew.getAmt());
                alipayCouponModel.setOpenId(citicNew.getOpenId());
                alipayCouponModel.setBusiId(citicNew.getId());
                alipayCouponModel.setStatus("");
                couponDetailMapper.addAliCouponDetail(alipayCouponModel);
            } else {
                citicNew.setRespMsg("退款："+response.getSubMsg());
                citicRefund(citicNew,citicNew.getRespMsg());
            }

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-农行首绑有礼-grantAlipayCoupon",ioe.getMessage());
        }
    }

    //全付通退款
    public void citicRefund(TCiticNew citicNew,
                             String reason){
        try{
            citicNew.setRefundFlag("1");
            citicNew.setRefundNo(SeqUtil.getSeqId());
            citicNew.setRespMsg(reason);

            //:{"RFUTRANJNLNO":"","RETMSG":"原支付订单信息不存在。","RETCODE":"XYRFD30","SETTLEDATE":"","PAYBANKNAME":"","UNDISCOUNTAMT":"","TRANENDDATE":"","DISCOUNTAMT":""}

            AjaxResult result = citicSendService.payRefund(citicNew.getOrderNo(),citicNew.getRefundNo(),
                    citicNew.getPayAmt(),citicNew.getPayAmt());
            if(result.isSuccess()){
                citicNew.setProcessed("4");
                JSONObject jsonObject = JSON.parseObject(result.get("data").toString());
                citicNew.setRespMsg(citicNew.getRespMsg() + "||,全付通："+jsonObject.getString("RETMSG"));
            } else {
                citicNew.setProcessed("3");
                citicNew.setRespMsg(citicNew.getRespMsg() +"||,全付通：" + result.getMsg());
            }
            citicNewMapper.updateRefundById(citicNew);

        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            //sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-农行首绑有礼-alipayRefund",ioe.getMessage());
        }
    }
}
